package controller;
import com.jfinal.aop.Clear;
import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.plugin.activerecord.Record;
import service.ICrudDemoServer;
import model.User;

import java.util.List;

/**
 * @Author: Raymond
 * @Date: 2020/7/13 16:49
 * @Description:
 */
public class HelloController extends Controller {

    //注入
    @Inject
    ICrudDemoServer iCrudDemoServer;

    public void index() {
        List<Record> recordList = iCrudDemoServer.findAll();
        setAttr("userList", recordList);
        render("detailed.html");
    }


    public void toupdate() {
        Integer id = Integer.valueOf(getPara( 0));
        User user = iCrudDemoServer.findOne(id);
        if ("1".equals(user.getSex())) {
            user.setSex("男");
        }else {
            user.setSex("女");
        }
        //相当于request.setAttribute
        set("Oneuser", user);
        //返回视图
        render("update.html");
    }

    public void update() {
        User user = getModel(User.class,"Oneuser");
        if("男".equals(user.getSex())){
            user.setSex("1");
        }else if("女".equals(user.getSex())){
            user.setSex("2");
        }
        String rus = iCrudDemoServer.update(user);
        System.out.println(rus);
        if ("1".equals(rus)) {
            //重定向
            redirect("/detil/index");
        }else {
            set("message","修改错误");
            redirect("/detil/toupdate/"+user.getId());
        }
    }

    public void toadd() {
        //renderJson("code","100");
        render("add.html");
    }

    public void add() {
        User user = getModel(User.class,"User");
        String rus = iCrudDemoServer.insertone(user);
        System.out.println(rus);
        if ("true".equals(rus)) {
            redirect("/detil/index");
        }else {
            set("message","修改错误");
            redirect("/detil/add");
        }
    }

    public void delete() {
        Integer id = Integer.valueOf(getPara( 0));
        System.out.println(id);
        String rus = iCrudDemoServer.delete(id);
        System.out.println(rus);
        redirect("/detil/index");
    }
}
